<?php

$conn = mysql_connect("localhost", "root", "yubaokeji");
mysql_select_db("analysis", $conn);
mysql_query("set names gbk");

$amxTime = date("Ym", strtotime("-2 month"));

$child = mysql_query("select * from ana_cash where c_month='" . $amxTime . "' and c_status=1 and c_agent=0 group by c_disid");
$rocord = mysql_num_rows($child);
if ($rocord > 0) {
    while ($info = mysql_fetch_array($child)) {
        $disi = mysql_query("select * from ana_disisbn where dis_id=" . $info['c_disid']);
        $dis_info = mysql_fetch_array($disi);
        $staff = mysql_query("select * from ana_salestaff where ssa_id=" . $dis_info['dis_ssaid']);
        $sta_info = mysql_fetch_array($staff);
        /** 处理结转 * */
        $count = mysql_query("select sum(c_in) as exten from ana_cash where c_status=1 and c_disid=" . $info['c_disid'] . " and c_month='" . $amxTime . "'");
        $money = mysql_fetch_array($count);
        $query = insertStaff(getpayeesn($dis_info["dis_custype"]), $money['exten'], $sta_info['ssa_bankname'], $sta_info['ssa_banktrans'], $sta_info['ssa_banknumber'], $amxTime, $sta_info['ssa_id'], null, $dis_info["dis_isbn"]);
        mysql_query($query);
        mysql_query("update ana_cash set c_status=0 where c_disid=" . $info['c_disid'] . " and c_month='" . $amxTime . "'");
    }
}


$parent = mysql_query("select * from ana_cash where c_month='" . $amxTime . "' and c_status=1 and c_disid=0 group by c_agent");
$precord = mysql_num_rows($parent);
if ($precord > 0) {
    while ($pinfo = mysql_fetch_array($parent)) {
        $agent = mysql_query("select * from ana_saleagent where sag_id=" . $pinfo['c_agent']);
        $ag_info = mysql_fetch_array($agent);
        /** 处理结转 * */
        $cou = mysql_query("select sum(c_in) as exten from ana_cash where c_status=1 and c_agent=" . $pinfo['c_agent'] . " and c_month='" . $amxTime . "'");
        $mon = mysql_fetch_array($cou);
        $que = insertStaff(getpayeesn($ag_info["sag_type"]), $mon['exten'], $ag_info['sag_payee'], $ag_info['sag_bank'], $ag_info['sag_baccount'], $amxTime, null, $pinfo['c_agent'], null);
        mysql_query($que);
        mysql_query("update ana_cash set c_status=0 where c_agent=" . $pinfo['c_agent'] . " and c_month='" . $amxTime . "'");
    }
}

function insertStaff($sn, $money, $name, $bank, $card, $month, $ssid, $agent, $dis)
{
    $val = "'" . $sn . "','" . $money . "','" . $name . "','" . $bank . "','" . $card . "','" . $month . "','" . $ssid . "','" . $agent . "','" . $dis . "','" . time() . "','100'";
    $sql = "insert into ana_settlement(set_sn,set_cash,set_asname,set_bank,set_bankcard,set_month,set_ssaid,set_agent,set_dis,set_time,set_status) value(" . $val . ")";
    return $sql;
}

function getpayeesn($type)
{
    return $type . rand(0, 9) . rand(0, 9) . date("ymd") . rand(10000, 99999);
}
